<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header">
        <el-row>
          <el-col :span="18">
            <dynamicBtn
              ref="btnRef"
              :deployId="taskForm.deployId"
              :procInsId="taskForm.procInsId"
              :taskId="taskForm.taskId"
              @saveData="handleSaveData"
            />
            <el-button
              type="success"
              @click="gotoContract"
              v-if="finished === 'true' && this.businessData.contractId"
              >修改合同信息</el-button>
            <!-- <el-button type="success" @click="handleComplete"
              v-if="finished === 'true' && !this.taskForm.procInsId">保存</el-button> -->
            <el-button
              type="success"
              @click="submitForm"
              v-if="finished === 'true' && !this.taskForm.taskId"
              >发起流程</el-button
            >
            <template v-if="finished === 'true' && this.taskForm.taskId">
              <el-button type="success" @click="handleSaveData">保存</el-button>
              <el-button type="success" @click="taskComplete">提交</el-button>
              <el-button type="warning" @click="handleAssign" v-if="taskForm.taskId"
                >转办</el-button
              >
              <!-- <el-button
                type="success"
                @click="handleDelegate"
                v-if="taskForm.taskId"
                >委派</el-button -->
              <!--                <el-button  icon="el-icon-edit-outline" type="primary"  @click="handleDelegate">签收</el-button>-->
              <el-button type="warning" @click="handleReturn">退回</el-button>
              <!--这里的驳回是退回到上一步环科院用不到所以先注释掉-->
              <!--<el-button type="danger" @click="handleReject">驳回</el-button>-->
            </template>
          </el-col>
          <el-col :span="6">
            <el-row style="justify-content: end">
              <el-button type="success" @click="printDateForm">打印</el-button>
              <el-button type="success" @click="exportDateFormPdf">导出pdf</el-button>
              <el-button type="success" @click="handleApproval">审批记录</el-button>
              <el-button type="success" @click="goBack" v-if="!isHide">返回</el-button>
            </el-row>
          </el-col>
        </el-row>
      </div>

      <el-row style="margin-top: 10px">
        <!--初始化流程加载表单信息-->
        <el-col :span="17" v-loading="formLoading">
          <el-tabs v-model="activityName" class="demo-tabs" v-if="formList.length > 1">
            <template v-for="(formItem, index) in formList">
              <el-tab-pane :label="formItem.tableName" :name="index">
                <templateForm
                  :form-data="formItem"
                  :finished="finished"
                  ref="formRef"
                  v-show="activityName == index"
                />
              </el-tab-pane>
            </template>
          </el-tabs>
          <templateForm
            :form-data="formList[0]"
            :finished="finished"
            @submit="submitForm"
            ref="formRef"
            v-if="formList.length == 1"
          />
        </el-col>
        <el-col :span="7">
          <div>
            <p class="pinformation">附件</p>
            <el-scrollbar>
              <fileUpload
                v-model="fileList"
                :autoUpload="true"
                :isDisplay="finished === 'true'"
                :fileType="[
                  'xls',
                  'xlsx',
                  'doc',
                  'docx',
                  'pdf',
                  'jpg',
                  'gif',
                  'bmp',
                  'png',
                ]"
              ></fileUpload>
              <span
                v-if="finished != 'true' && (!fileList || fileList.length == 0)"
                style="margin-left: 10px"
                >无</span
              >
            </el-scrollbar>
            <p class="pinformation">审批记录</p>
            <el-scrollbar
              v-loading="scrLoading"
              :height="recordHeight"
              ref="recodScrollbarRef"
            >
              <el-timeline style="padding-left: 5px !important" v-if="flowRecordList">
                <el-timeline-item
                  v-for="(item, index) in flowRecordList"
                  :key="index"
                  :icon="setIcon(item.finishTime)"
                  :color="setColor(item.finishTime)"
                >
                  <p style="font-weight: 700">{{ item.taskName }}</p>
                  <el-descriptions :column="1" size="small" border>
                    <el-descriptions-item
                      v-if="item.assigneeName"
                      label-class-name="my-label"
                    >
                      <template slot="label"
                        ><i class="el-icon-user"></i>实际办理</template
                      >
                      {{ item.assigneeName }}
                      <el-tag type="info">{{ item.deptName }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item
                      v-if="item.candidate"
                      label-class-name="my-label"
                    >
                      <template slot="label"
                        ><i class="el-icon-user"></i>候选办理</template
                      >
                      {{ item.candidate }}
                    </el-descriptions-item>
                    <el-descriptions-item label-class-name="my-label">
                      <template slot="label"
                        ><i class="el-icon-date"></i>接收时间</template
                      >
                      {{ item.createTime }}
                    </el-descriptions-item>
                    <el-descriptions-item
                      v-if="item.finishTime"
                      label-class-name="my-label"
                    >
                      <template slot="label"
                        ><i class="el-icon-date"></i>处理时间</template
                      >
                      {{ item.finishTime }}
                    </el-descriptions-item>
                    <el-descriptions-item
                      v-if="item.duration"
                      label-class-name="my-label"
                    >
                      <template slot="label"><i class="el-icon-time"></i>耗时</template>
                      {{ item.duration }}
                    </el-descriptions-item>
                    <el-descriptions-item v-if="item.comment" label-class-name="my-label">
                      <template slot="label"
                        ><i class="el-icon-tickets"></i>处理意见</template
                      >
                      {{ item.comment.comment }}
                    </el-descriptions-item>
                  </el-descriptions>

                  <!--                    <p  v-if="item.comment">-->
                  <!--                      <el-tag type="success" v-if="item.comment.type === '1'">  {{item.comment.comment}}</el-tag>-->
                  <!--                      <el-tag type="warning" v-if="item.comment.type === '2'">  {{item.comment.comment}}</el-tag>-->
                  <!--                      <el-tag type="danger" v-if="item.comment.type === '3'">  {{item.comment.comment}}</el-tag>-->
                  <!--                    </p>-->
                </el-timeline-item>
              </el-timeline>
              <div v-else style="text-align: center; font-size: 15px; color: #909399">
                暂无数据
              </div>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="open"
      title="审批记录"
      width="90%"
    >
      <el-row>
        <el-col :span="7" v-if="flowRecordList" style="padding-right: 15px">
          <p class="pinformation">审批记录</p>
          <el-scrollbar height="70vh">
            <el-timeline style="padding-left: 5px !important">
              <el-timeline-item
                v-for="(item, index) in flowRecordList"
                :key="index"
                :icon="setIcon(item.finishTime)"
                :color="setColor(item.finishTime)"
              >
                <p style="font-weight: 700">{{ item.taskName }}</p>
                <el-descriptions :column="1" size="small" border>
                  <el-descriptions-item
                    v-if="item.assigneeName"
                    label-class-name="my-label"
                  >
                    <template slot="label"><i class="el-icon-user"></i>实际办理</template>
                    {{ item.assigneeName }}
                    <el-tag type="info">{{ item.deptName }}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item v-if="item.candidate" label-class-name="my-label">
                    <template slot="label"><i class="el-icon-user"></i>候选办理</template>
                    {{ item.candidate }}
                  </el-descriptions-item>
                  <el-descriptions-item label-class-name="my-label">
                    <template slot="label"><i class="el-icon-date"></i>接收时间</template>
                    {{ item.createTime }}
                  </el-descriptions-item>
                  <el-descriptions-item
                    v-if="item.finishTime"
                    label-class-name="my-label"
                  >
                    <template slot="label"><i class="el-icon-date"></i>处理时间</template>
                    {{ item.finishTime }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="item.duration" label-class-name="my-label">
                    <template slot="label"><i class="el-icon-time"></i>耗时</template>
                    {{ item.duration }}
                  </el-descriptions-item>
                  <el-descriptions-item v-if="item.comment" label-class-name="my-label">
                    <template slot="label"
                      ><i class="el-icon-tickets"></i>处理意见</template
                    >
                    {{ item.comment.comment }}
                  </el-descriptions-item>
                </el-descriptions>

                <!--                    <p  v-if="item.comment">-->
                <!--                      <el-tag type="success" v-if="item.comment.type === '1'">  {{item.comment.comment}}</el-tag>-->
                <!--                      <el-tag type="warning" v-if="item.comment.type === '2'">  {{item.comment.comment}}</el-tag>-->
                <!--                      <el-tag type="danger" v-if="item.comment.type === '3'">  {{item.comment.comment}}</el-tag>-->
                <!--                    </p>-->
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </el-col>
        <el-col
          :span="flowRecordList ? 17 : 24"
          :style="'border-left:' + (flowRecordList ? '3' : '0') + 'px #ddd solid;'"
          style="padding-left: 15px"
        >
          <p class="pinformation">流程图</p>
          <flow :xmlData="xmlData" :taskData="taskList"></flow>
        </el-col>
      </el-row>
    </el-dialog>
    <!--审批正常流程-->
    <el-dialog
      :class="'el-dialog-theme3'"
      :title="completeTitle"
      v-model="completeOpen"
      :width="checkSendUser ? '60%' : '40%'"
      append-to-body
    >
      <el-form ref="taskForm" :model="taskForm" label-width="80px">
        <el-form-item v-if="checkSendUser" prop="targetKey">
          <el-row :gutter="20">
            <!--部门数据-->
            <el-col :span="6" :xs="24">
              <h6>部门列表</h6>
              <div class="head-container">
                <el-input
                  v-model="deptName"
                  placeholder="请输入部门名称"
                  clearable
                  size="small"
                  prefix-icon="el-icon-search"
                  style="margin-bottom: 20px"
                />
              </div>
              <div class="head-container">
                <el-tree
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  :filter-node-method="filterNode"
                  ref="tree"
                  default-expand-all
                  @node-click="handleNodeClick"
                />
              </div>
            </el-col>
            <el-col :span="10" :xs="24">
              <h6>待选人员</h6>
              <el-table
                ref="singleTable"
                :data="userList"
                border
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column label="用户名" align="center" prop="nickName" />
                <el-table-column label="部门" align="center" prop="dept.deptName" />
              </el-table>
            </el-col>
            <el-col :span="8" :xs="24">
              <h6>已选人员</h6>
              <el-tag
                v-for="(user, index) in userData"
                :key="index"
                closable
                @close="handleClose(user)"
              >
                {{ user.nickName }} {{ user.dept.deptName }}
              </el-tag>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item
          label="处理意见"
          prop="comment"
          :rules="[{ required: true, message: '请输入处理意见', trigger: 'blur' }]"
        >
          <el-input
            type="textarea"
            v-model="taskForm.comment"
            placeholder="请输入处理意见"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="completeOpen = false">取 消</el-button>
        <el-button type="primary" @click="taskComplete">确 定</el-button>
      </span>
    </el-dialog>

    <!--退回流程-->
    <el-dialog
      :class="'el-dialog-theme3'"
      :title="returnTitle"
      v-model="returnOpen"
      width="40%"
      append-to-body
    >
      <el-form ref="taskForm" :model="taskForm" label-width="80">
        <el-form-item
          label="退回节点："
          prop="targetKey"
          :rules="[{ required: true, message: '请选择退回节点', trigger: 'blur' }]"
        >
          <el-radio-group v-model="taskForm.targetKey" v-if="returnTaskList.length > 0">
            <el-radio-button
              v-for="item in returnTaskList"
              :key="item.id"
              :label="item.id"
              >{{ item.name }}</el-radio-button
            >
          </el-radio-group>
          <span v-else style="color: red">没有可退回的流程</span>
        </el-form-item>
        <el-form-item
          label="退回意见："
          prop="comment"
          :rules="[{ message: '请输入意见', trigger: 'blur' }]"
        >
          <el-input
            style="width: 100%"
            :autosize="{ minRows: 10, maxRows: 20 }"
            type="textarea"
            v-model="taskForm.comment"
            placeholder="请输入意见"
            v-if="returnTaskList.length > 0"
          />
          <span v-else style="color: red">没有可退回的流程</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="taskReturn" v-if="returnTaskList.length > 0"
            >确 定</el-button
          >
          <el-button type="danger" @click="returnOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 转办 -->
    <el-dialog
      :class="'el-dialog-theme3'"
      append-to-body
      draggable
      :close-on-click-modal="false"
      v-model="userOpen"
      title="选择人员"
      @close="userClose"
      width="500px"
    >
      <el-input
        style="margin-bottom: 10px"
        v-model="filterText"
        clearable
        placeholder="请输入人员名称"
        prefix-icon="UserFilled"
      >
      </el-input>
      <el-scrollbar height="50vh" ref="scrollbarRef">
        <el-tree
          :data="treeData"
          :props="defaultProps1"
          :default-expand-all="true"
          @node-click="nodeClick"
          node-key="userId"
          :highlight-current="true"
          ref="treeRef"
          v-loading="treeLoading"
          :filter-node-method="filterNode1"
        />
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="determine">确 定</el-button>
          <el-button type="danger" @click="userOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--驳回流程-->
    <el-dialog
      :class="'el-dialog-theme3'"
      :title="rejectTitle"
      v-model="rejectOpen"
      width="40%"
      append-to-body
      @close="cancelDelegateTask"
    >
      <el-form ref="taskForm" :model="taskForm" label-width="80px">
        <el-form-item
          label="驳回意见："
          prop="comment"
          :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]"
        >
          <el-input
            style="width: 50%"
            type="textarea"
            v-model="taskForm.comment"
            placeholder="请输入意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="taskReject">确 定</el-button>
          <el-button type="danger" @click="rejectOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { flowRecord, queryFileList } from "@/api/flowable/finished";
import TemplateForm from "@/components/TemplateForm";
import dynamicBtn from "@/views/dynamic";

import {
  definitionStart,
  getProcessFormData,
  readXml,
  getFlowViewer,
} from "@/api/flowable/definition";
import {
  complete,
  saveData,
  rejectTask,
  returnList,
  returnTask,
  getNextFlowNode,
  delegate,
  assignTask,
  delegateTask,
  getProcessDefinition,
} from "@/api/flowable/todo";
import flow from "@/views/flowable/task/record/flow";
import { listUser } from "@/api/system/user";
import bus from "@/utils/eventBus";
import useRouteView from "@/store/modules/routeView";
import { getTree } from "@/api/myTask/myTask";
import { getTreeList } from "@/api/system/newUser";

export default {
  name: "taskRecord",
  components: {
    flow,
    TemplateForm,
    dynamicBtn,
  },
  props: {
    isHide: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      sign: null,
      userOpen: false,
      filterText: "",
      scrLoading: false,
      businessData: {},
      formLoading: false,
      // 遮罩层
      routeViewStore: useRouteView(),
      // 模型xml数据
      xmlData: "",
      taskList: [],
      treeData: [],
      treeLoading: false,
      defaultProps1: { label: "nickName", children: "children" },
      userId: "",
      activityName: 0,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      // 用户表格数据
      userList: null,
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        deptId: undefined,
      },
      // 遮罩层
      loading: true,
      flowRecordList: [], // 流程流转数据
      fileList: undefined,
      formConfCopy: {},
      src: null,
      rules: {}, // 表单校验
      variablesForm: {}, // 流程变量数据
      taskForm: {
        returnTaskShow: false, // 是否展示回退表单
        delegateTaskShow: false, // 是否展示回退表单
        defaultTaskShow: true, // 默认处理
        sendUserShow: false, // 审批用户
        multiple: false,
        comment: "", // 意见内容
        procInsId: "", // 流程实例编号
        instanceId: "", // 流程实例编号
        deployId: "", // 流程定义编号
        taskId: "", // 流程任务编号
        vars: "",
        targetKey: "",
      },
      userDataList: [], // 流程候选人
      assignee: null,
      formList: [], // 默认表单数据
      variables: [], // 流程变量数据
      variablesData: {}, // 流程变量数据
      variableOpen: false, // 是否加载流程变量数据
      returnTaskList: [], // 回退列表数据
      finished: "false",
      completeTitle: null,
      completeOpen: false,
      open: false,
      returnTitle: null,
      returnOpen: false,
      rejectOpen: false,
      rejectTitle: null,
      userData: [],
      path: this.$route.query.path,
      checkSendUser: false, // 是否展示选择人员模块
      recordHeight: 0,
      //testPath: '@/views/contract/check/business.vue',
    };
  },
  created() {
    bus.off("searchWithTable");
    bus.off("refresh");
    bus.on("refresh", () => {
      this.formList = [];
      this.processFormData();
    });
    const { path, name, meta } = this.$route;
    this.routeViewStore.setRouteView1({ path, name, meta });
    if (Object.keys(this.$route.query).length > 0) {
      this.taskForm.deployId = this.$route.query && this.$route.query.deployId;
      this.taskForm.taskId = this.$route.query && this.$route.query.taskId;
      this.taskForm.procInsId = this.$route.query && this.$route.query.procInsId;
      this.taskForm.executionId = this.$route.query && this.$route.query.executionId;
      this.taskForm.instanceId = this.$route.query && this.$route.query.procInsId;
      this.finished = this.$route.query && this.$route.query.finished;
      this.queryProcessDefinition();
      // 流程任务重获取变量表单
      if (this.taskForm.taskId) {
        this.getNextFlowNode(this.taskForm.taskId);
      }
    }
  },

  mounted() {
    const params = Object.keys(this.$route.query);
    if (
      params.length != 0 &&
      (params.includes("deployId") ||
        params.includes("procInsId") ||
        params.includes("taskId"))
    ) {
      this.setBusinessData();
      this.processFormData();
    }
    this.getHeight();
  },

  watch: {
    filterText(val) {
      this.$refs.treeRef.filter(val);
    },
    // fileList(val) {
    //   debugger;
    //   this.businessData.fileIds = val.map((item) => {
    //     return item.fileId;
    //   });
    // },
  },

  methods: {
    // 任务进度详情基本信息调用
    getInfo(procInsId) {
      this.formList = [];
      this.businessData = {};
      this.taskForm.procInsId = procInsId;
      // 初始化表单
      this.setBusinessData();
      this.processFormData();
      this.getFlowRecordList(this.taskForm.procInsId);
      this.getFileList(this.taskForm.procInsId);
    },
    queryProcessDefinition() {
      if (this.taskForm.deployId) {
        this.getModelDetail(this.taskForm.deployId);
      }
      if (this.taskForm.procInsId) {
        // 回显流程记录
        if (this.taskForm.executionId) {
          this.getFlowViewer(this.taskForm.procInsId, this.taskForm.executionId);
        }
        this.getFlowRecordList(this.taskForm.procInsId);
        this.getFileList(this.taskForm.procInsId);
      }
      if (!this.taskForm.taskId) return;
      getProcessDefinition(this.taskForm.taskId).then((res) => {
        if (res.code == 200) {
          if (!this.taskForm.deployId) {
            this.taskForm.deployId = res.data.deployId;
            this.getModelDetail(this.taskForm.deployId);
          }
          if (!this.taskForm.procInsId) {
            this.taskForm.procInsId = res.data.procInsId;
            this.getFlowRecordList(this.taskForm.procInsId);
            this.getFileList(this.taskForm.procInsId);
          }
          if (!this.taskForm.executionId) {
            this.taskForm.executionId = res.data.executionId;
            // 回显流程记录
            this.getFlowViewer(this.taskForm.procInsId, this.taskForm.executionId);
          }
        }
      });
    },
    gotoContract() {
      this.$tab.closePage().then(() => {
        let queryParams = {
          contractId: this.businessData.contractId,
        };
        if (this.taskForm.taskId) {
          queryParams.taskId = this.taskForm.taskId;
        }
        this.$router.push({ path: "/contract/check", query: queryParams });
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {},
    /** 查询用户列表 */
    getList() {
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.userList = response.rows;
        this.total = response.total;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    filterNode1(value, data) {
      if (!value) {
        return true; // 如果搜索框为空，则显示所有节点
      }
      return data.nickName.includes(value); // 根据节点的 groupName 属性进行名称过滤
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },

    nodeClick(val) {
      this.userId = "";
      if (val.userType == 1) {
        this.userId = val.userId;
      }
    },
    /** xml 文件 */
    getModelDetail(deployId) {
      // 发送请求，获取xml
      readXml(deployId).then((res) => {
        this.xmlData = res.data;
      });
    },
    getFlowViewer(procInsId, executionId) {
      if (!executionId) return;
      getFlowViewer(procInsId, executionId).then((res) => {
        this.taskList = res.data;
      });
    },
    setIcon(val) {
      if (val) {
        return "el-icon-check";
      } else {
        return "el-icon-time";
      }
    },
    setColor(val) {
      if (val) {
        return "#2bc418";
      } else {
        return "#b3bdbb";
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection) {
        this.userData = selection;
        const selectVal = selection.map((item) => item.userId);
        if (selectVal instanceof Array) {
          this.taskForm.values = {
            approval: selectVal.join(","),
          };
        } else {
          this.taskForm.values = {
            approval: selectVal,
          };
        }
      }
    },
    // 关闭标签
    handleClose(tag) {
      this.userData.splice(this.userData.indexOf(tag), 1);
      this.$refs.singleTable.toggleRowSelection(tag, false);
    },
    /** 流程变量赋值 */
    handleCheckChange(val) {
      if (val instanceof Array) {
        this.taskForm.values = {
          approval: val.join(","),
        };
      } else {
        this.taskForm.values = {
          approval: val,
        };
      }
    },
    /** 流程流转记录 */
    getFlowRecordList(procInsId) {
      if (!procInsId) return;
      const params = { procInsId: procInsId };
      this.scrLoading = true;
      flowRecord(params)
        .then((res) => {
          this.scrLoading = false;
          this.flowRecordList = res.data.flowList;
        })
        .catch((res) => {
          this.scrLoading = false;
          this.goBack();
        });
    },
    /** 流程流转记录 */
    getFileList(procInsId) {
      if (!procInsId) return;
      const params = { procInsId: procInsId };
      queryFileList(params)
        .then((res) => {
          if (!this.fileList && res.data.length == 0) {
            return;
          }
          this.fileList = res.data;
        })
        .catch((res) => {});
    },
    fillFormData(form, data) {
      form.fields.forEach((item) => {
        const val = data[item.__vModel__];
        if (val) {
          item.__config__.defaultValue = val;
        }
      });
    },

    setBusinessData() {
      let params = this.$route.query;
      for (let param in params) {
        if (param.startsWith("v_")) {
          this.businessData[param.substring(2)] = params[param];
        }
      }
      // if (Object.keys(this.businessData).length > 0) {
      if (this.finished == "true") {
        this.$refs.btnRef.queryBusBtnList(this.businessData);
      }
      // }
    },
    /** 获取流程表单数据 */
    processFormData() {
      // 提交流程申请时填写的表单存入了流程变量中后续任务处理时需要展示
      this.taskForm.params = this.businessData;
      this.formLoading = true;
      getProcessFormData(this.taskForm).then((res) => {
        // this.variables = res.data.variables;
        this.formList = res.data.formList;
        this.formLoading = false;
        this.variableOpen = true;
        if (res.data.variables) {
          this.businessData = res.data.variables;
          if (this.finished == "true") {
            this.$refs.btnRef.queryBusBtnList(this.businessData);
          }
        }
      });
    },

    /** 根据当前任务或者流程设计配置的下一步节点 */
    getNextFlowNode(taskId) {
      // 根据当前任务或者流程设计配置的下一步节点 todo 暂时未涉及到考虑网关、表达式和多节点情况
      const params = { taskId: taskId };
      getNextFlowNode(params).then((res) => {
        const data = res.data;
        if (data) {
          this.checkSendUser = true;
          if (data.type === "assignee") {
            // 指定人员
            this.userDataList = res.data.userList;
          } else if (data.type === "candidateUsers") {
            // 指定人员(多个)
            this.userDataList = res.data.userList;
            this.taskForm.multiple = true;
          } else if (data.type === "candidateGroups") {
            // 指定组(所属角色接收任务)
            res.data.roleList.forEach((role) => {
              role.userId = role.roleId;
              role.nickName = role.roleName;
            });
            this.userDataList = res.data.roleList;
            this.taskForm.multiple = false;
          } else if (data.type === "multiInstance") {
            // 会签?
            this.userDataList = res.data.userList;
            this.taskForm.multiple = true;
          } else if (data.type === "fixed") {
            // 已经固定人员接收下一任务
            this.checkSendUser = false;
          }
        }
      });
    },

    /** 审批任务选择 */
    handleComplete() {
      this.completeOpen = true;
      this.completeTitle = "审批流程";
      this.getTreeselect();
    },
    handleSaveData(callback){
      let formDataArray = [];
      if (this.$refs.formRef instanceof Array) {
        this.$refs.formRef.forEach((itemForm) => {
          let formData = itemForm.getFormData();
          if (formData) {
            formDataArray.push(formData);
          }
        });
        if (formDataArray.length != this.$refs.formRef.length) return;
      } else if (typeof this.$refs.formRef == "object") {
        let formData = this.$refs.formRef.getFormData();
        if (!formData) return;
        formDataArray.push(formData);
      }
      if (!this.taskForm.values && this.checkSendUser) {
        bus.emit("dbSave", true);
        this.$modal.msgError("当前任务已提交！");
        this.goBack();
        return;
      }
      this.taskForm.values = { formDatas: formDataArray };
      if (this.fileList) {
        this.taskForm.values.fileIds = this.fileList.map((item) => {
          return item.fileId;
        });
      }
      this.$modal.loading("正在保存，请稍候...");
      saveData(this.taskForm)
        .then((response) => {
          this.$modal.closeLoading();
          if (typeof callback === 'function'){
            callback();
          }else{
            this.$modal.msgSuccess("保存成功！");
          }
        })
        .catch(() => {
          this.$modal.closeLoading();
        });
    },
    /** 审批任务 */
    taskComplete() {
      let formDataArray = [];
      if (this.$refs.formRef instanceof Array) {
        this.$refs.formRef.forEach((itemForm) => {
          let formData = itemForm.getFormData();
          if (formData) {
            formDataArray.push(formData);
          }
        });
        if (formDataArray.length != this.$refs.formRef.length) return;
      } else if (typeof this.$refs.formRef == "object") {
        let formData = this.$refs.formRef.getFormData();
        if (!formData) return;
        formDataArray.push(formData);
      }
      this.$modal
        .confirm("确定要提交吗?")
        .then(async () => {
          if (!this.taskForm.values && this.checkSendUser) {
            bus.emit("dbSave", true);
            this.$modal.msgError("当前任务已提交！");
            this.goBack();
          }
          this.taskForm.values = { formDatas: formDataArray };
          if (this.fileList) {
            this.taskForm.values.fileIds = this.fileList.map((item) => {
              return item.fileId;
            });
          }
          this.$modal.loading("正在提交，请稍候...");
          complete(this.taskForm)
            .then((response) => {
              this.$modal.msgSuccess(response.msg);
              bus.emit("dbSave", true);
              this.goBack();
              this.$modal.closeLoading();
            })
            .catch(() => {
              this.$modal.closeLoading();
            });
        })
        .catch(() => {});
    },
    /** 委派任务 */
    handleDelegate() {
      this.userOpen = true;
      this.treeLoading = true;
      this.sign = 2;
      getTree().then((res) => {
        this.treeLoading = false;
        this.treeData = res.data;
      });
    },
    handleAssign() {
      this.userOpen = true;
      this.treeLoading = true;
      this.sign = 1;
      getTreeList().then((res) => {
        this.treeLoading = false;
        this.treeData = this.handleTree(res.data, "userId");
      });
    },
    userClose() {
      this.treeData = [];
      this.filterText = "";
      this.userId = "";
    },
    determine() {
      if (!this.userId) return this.$modal.msgError("请选择人员");
      if (this.sign == 1) {
        this.$modal.loading("正在转办，请稍候...");
        assignTask({
          assignee: this.userId,
          taskId: this.taskForm.taskId,
        })
          .then((res) => {
            this.$modal.msgSuccess("转办成功");
            this.userOpen = false;
            this.goBack();
            this.$modal.closeLoading();
          })
          .catch(() => {
            this.$modal.closeLoading();
          });
      } else {
        this.$modal.loading("正在委派，请稍候...");
        delegateTask({
          assignee: this.userId,
          taskId: this.taskForm.taskId,
        })
          .then((res) => {
            this.$modal.msgSuccess("委派成功");
            this.userOpen = false;
            this.goBack();
            this.$modal.closeLoading();
          })
          .catch(() => {
            this.$modal.closeLoading();
          });
      }
    },
    /** 返回页面 */
    goBack() {
      // 关闭当前标签页并返回上个页面
      this.$tab.closePage().then(() => {
        this.$router.push(this.path);
      });
    },
    /** 接收子组件传的值 */
    getData(data) {
      if (data) {
        const variables = [];
        data.fields.forEach((item) => {
          let variableData = {};
          variableData.label = item.__config__.label;
          // 表单值为多个选项时
          if (item.__config__.defaultValue instanceof Array) {
            const array = [];
            item.__config__.defaultValue.forEach((val) => {
              array.push(val);
            });
            variableData.val = array;
          } else {
            variableData.val = item.__config__.defaultValue;
          }
          variables.push(variableData);
        });
        this.variables = variables;
      }
    },
    /** 申请流程表单数据提交 */
    submitForm() {
      let formDataArray = [];
      if (this.$refs.formRef instanceof Array) {
        this.$refs.formRef.forEach((itemForm) => {
          let formData = itemForm.getFormData();
          if (formData) {
            formDataArray.push(formData);
          }
        });
        if (formDataArray.length != this.$refs.formRef.length) return;
      } else if (typeof this.$refs.formRef == "object") {
        let formData = this.$refs.formRef.getFormData();
        if (!formData) return;
        formDataArray.push(formData);
      }
      this.$modal
        .confirm("确定要提交吗?")
        .then(async () => {
          this.$modal.loading("正在提交，请稍候...");
          if (this.taskForm.deployId) {
            let data = {};
            data.variables = { formDatas: formDataArray };
            if (this.businessData) {
              data.variables.params = this.businessData;
            }
            if (this.fileList) {
              data.variables.fileIds = this.fileList.map((item) => {
                return item.fileId;
              });
            }
            // 启动流程并将表单数据加入流程变量
            definitionStart(this.taskForm.deployId, data.variables)
              .then((res) => {
                bus.emit("dbSave", true);
                this.$modal.msgSuccess("提交成功！");
                this.$modal.closeLoading();
                this.goBack();
              })
              .catch(() => {
                this.$modal.closeLoading();
              });
          }
        })
        .catch(() => {});
    },
    handleApproval() {
      this.open = true;
    },
    exportDateFormPdf() {
      this.download(
        "/flowable/task/exportPdf/" + this.taskForm.procInsId,
        {},
        `表单.pdf`
      );
    },
    printDateForm() {
      this.$refs.formRef.printDateForm();
    },
    /** 驳回任务 */
    handleReject() {
      this.rejectOpen = true;
      this.rejectTitle = "驳回流程";
    },
    /** 驳回任务 */
    taskReject() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          this.$modal.loading("正在驳回，请稍候...");
          rejectTask(this.taskForm)
            .then((res) => {
              this.$modal.msgSuccess(res.msg);
              this.rejectOpen = false;
              this.goBack();
              this.$modal.closeLoading();
            })
            .catch(() => {
              this.$modal.closeLoading();
            });
        }
      });
    },
    /** 可退回任务列表 */
    handleReturn() {
      this.returnOpen = true;
      this.returnTitle = "退回流程";
      returnList(this.taskForm).then((res) => {
        if (!res.data) return;
        this.returnTaskList = res.data;
        this.taskForm.values = null;
        this.taskForm.targetKey = this.returnTaskList[this.returnTaskList.length - 1].id;
      });
    },
    /** 提交退回任务 */
    taskReturn() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          let formDataArray = [];
          if (this.$refs.formRef instanceof Array) {
            this.$refs.formRef.forEach((itemForm) => {
              let formData = itemForm.getFormData();
              if (formData) {
                formDataArray.push(formData);
              }
            });
            if (formDataArray.length != this.$refs.formRef.length) return;
          } else if (typeof this.$refs.formRef == "object") {
            let formData = this.$refs.formRef.getFormData();
            if (!formData) return;
            formDataArray.push(formData);
          }
          this.taskForm.values = { formDatas: formDataArray };
          if (this.fileList) {
            this.taskForm.values.fileIds = this.fileList.map((item) => {
              return item.fileId;
            });
          }
          this.$modal.loading("正在退回，请稍候...");
          returnTask(this.taskForm)
            .then((res) => {
              this.diaClose();
              bus.emit("dbSave", true);
              this.$modal.msgSuccess(res.msg);
              this.returnOpen = false;
              this.goBack();
              this.$modal.closeLoading();
            })
            .catch(() => {
              this.diaClose();
              this.$modal.closeLoading();
            });
        }
      });
    },
    /** 取消回退任务按钮 */
    diaClose() {
      // this.taskForm.returnTaskShow = false;
      // this.taskForm.defaultTaskShow = true;
      // this.taskForm.sendUserShow = true;
      this.returnTaskList = [];
      this.taskForm.targetKey = "";
      this.taskForm.comment = "";
      this.$refs["taskForm"]?.clearValidate();
    },
    /** 委派任务 */
    submitDeleteTask() {
      this.$refs["taskForm"].validate((valid) => {
        if (valid) {
          delegate(this.taskForm).then((response) => {
            this.$modal.msgSuccess(response.msg);
            this.goBack();
          });
        }
      });
    },
    /** 取消回退任务按钮 */
    cancelDelegateTask() {
      // this.taskForm.delegateTaskShow = false;
      // this.taskForm.defaultTaskShow = true;
      // this.taskForm.sendUserShow = true;
      // this.returnTaskList = [];
      this.taskForm.comment = "";
      this.$refs["taskForm"]?.clearValidate();
    },
    getHeight() {
      nextTick(() => {
        this.recordHeight = this.getSubFileHeight(this, "recodScrollbarRef", 20);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.test-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.my-label {
  background: #e1f3d8;
}
</style>
